<?php
declare (strict_types = 1);

namespace app\service\logic\common\trtc;

use app\model\communal\TrtcRoomsModel;
use app\service\logic\BaseService;

final class TrtcRoomsService extends BaseService
{
    protected string $modelClassName = 'TrtcRoomsModel';

    /**
     * @param $params
     */
    public function roomEvent($params)
    {
        if (isset($params['EventType']) && isset($params['EventInfo'])) {
            $EventInfo = $params['EventInfo'];
            $UserIdArray = explode('_', $EventInfo['UserId']);
            $RoomId = $EventInfo['RoomId'];
            if (in_array($UserIdArray[1], ['expert', 'user'])) {
                $type = $UserIdArray[1] == 'expert' ? 2 : 1;
                $where = ['type' => $type, 'morph_id' => $UserIdArray[2], 'room_id' => $RoomId];
                $model = TrtcRoomsModel::where($where)->findOrEmpty();
                switch ($params['EventType']) {
                    case 103:
                        // 进房
                        if ($model->isEmpty()) {
                            $model->save($where);
                        }
                        break;
                    case 104:
                        // 退房
                        if (!$model->isEmpty()) {
                            $model->delete();
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    /**
     * 根据多态id获取房间号
     *
     * @param $morphId
     * @param $type
     * @return array
     */
    public function getRoomIdsByMorIdType($morphId, $type)
    {
        return TrtcRoomsModel::where(['morph_id' => $morphId, 'type' => $type])->column('room_id');
    }
}
